package org.yasukusury.crawler.helper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.yasukusury.crawler.dao.List;
import org.yasukusury.crawler.mapper.CopyMapper;
import org.yasukusury.crawler.mapper.ListMapper;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Y
 * Date: 2017-11-16
 * Time: 16:09
 */
public class Statistics {

    private static final String resource = "mybatis-config.xml";

    public void start(java.util.List<String> asins) throws IOException {

        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession session = sessionFactory.openSession(false);
        ListMapper listMapper = session.getMapper(ListMapper.class);

        try {
            for (String asin : asins) {
                List list = listMapper.select(asin);
                if (list != null) {
                    int five, four, three, two, one, total;
                    double avg;
                    five = listMapper.stat(asin, 5);
                    four = listMapper.stat(asin, 4);
                    three = listMapper.stat(asin, 3);
                    two = listMapper.stat(asin, 2);
                    one = listMapper.stat(asin, 1);
                    total = five + four + three + two + one;
                    avg = (5.0 * five + 4.0 * four + 3.0 * three + 2.0 * two + one) / total;
                    list.setFiveVp(five);
                    list.setFourVp(four);
                    list.setThreeVp(three);
                    list.setTwoVp(two);
                    list.setOneVp(one);
                    list.setStar(avg);
                    list.setTotalVpCount(total);
                    listMapper.update(list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
        session.commit();
        session.close();
    }
}
